package com.yc.hwc.biz;

import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;

import com.yc.hwc.bean.User;
import com.yc.hwc.dao.IUserExDao;

@Service
public class UserBiz extends BaseBiz<User> {

	public void setDao(JpaRepository<User, Long> dao) {
		// 废弃;
	}

	@Autowired
	public void setDao(IUserExDao dao) {
		this.dao = dao;
	}

	@Override
	protected boolean validate(User e, Errors es) throws BizException {
		String[] names = null;
		if (e.getId() == null && e.getAccount() == null && e.getName() != null) {
			e.setName(e.getName().replaceAll("\\s+", ""));
			names = e.getName().split("[,.;:，。；：]");
		}
		if (names == null || names.length <= 1) {
			if (e.getAccount() != null) {
				int acnt = ((IUserExDao) dao).countByAccountAndIdNot(e.getAccount(), e.getId());
				if (acnt > 0) {
					es.rejectValue("account", "account.error", "该账号已经被其它用户使用！");
				}
			}
			if (e.getEmail() != null) {
				int ecnt = ((IUserExDao) dao).countByEmailAndIdNot(e.getEmail(), e.getId());
				if (ecnt > 0) {
					es.rejectValue("email", "email.error", "该邮箱已经被其它用户使用！");
				}
			}
			return super.validate(e, es);
		} else {
			Random r = new Random();
			for (String name : names) {
				User u = new User();
				u.setName(name);
				u.setAccount(name);
				u.setPwd("123456");
				u.setClsSn(e.getClsSn());
				u.setRole((byte) 1);
				u.setHead("image/head/" + (r.nextInt(15) + 1) + ".gif");
				dao.save(u);
			}
			return false;
		}
	}

}
